package development.app.mxh;

import iplayparticle.view.iplayparticleResources;

import java.util.Vector;

import particle.core.platform.IPlatformPictureImportEventHandler;
import particle.core.platform.Platform;
import particle.core.platform.PlatformPictureImportEvent;
import particle.core.tools.ByteBuffer;
import particle.core.view.assets.Image;
import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TimerListener;
import state.component.BottomBar;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.GameScrollBar;
import state.component.GridMenu;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.CheckBoxArray;
import state.util.array.GameImageArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.FrmDownloadResource;
import development.Global;
import development.bean.Category;
import development.bean.Comment;
import development.group.FrmGroup18Plus;
import development.group.FrmGroupKetBanMangXHChat;
import development.group.FrmGroupMenu;
import development.group.FrmGroupNapXuAndExchangeGold;
import development.socket.SocketClientUtil;

public class FrmMyAlbum extends GameForm implements EventListener, TimerListener, IPlatformPictureImportEventHandler {
  public static final int LIST_MY_ALBUM_REQUEST = 560;
  public static final int LIST_MY_ALBUM_RESPONSE = 561;

  public static final int CREATED_ALBUM_REQUEST = 562;
  public static final int CREATED_ALBUM_RESPONSE = 563;

  public static final int DELTE_ALBUM_REQUEST = 564;
  public static final int DELETE_ALBUM_RESPONSE = 565;

  public static final int CHANGE_ALBUM_NAME_REQUEST = 566;
  public static final int CHANGE_ALBUM_NAME_RESPONSE = 567;

  public static final int CHANGE_ROLE_REQUEST = 568;

  public static final int CREATE_PHOTO_REQUEST = 569;
  public static final int CREATE_PHOTO_RESPONSE = 570;

  public static final int LIST_PHOTO_REQUEST = 571;
  public static final int LIST_PHOTO_RESPONSE = 572;

  public static final int VIEW_PHOTO_REQUEST = 573;
  public static final int VIEW_PHOTO_RESPONSE = 574;

  public static final int VIEW_ZOOM_PHOTO_REQUEST = 575;
  public static final int VIEW_ZOOM_PHOTO_RESPONSE = 576;

  public static final int LIKE_PHOTO_REQUEST = 577;
  public static final int LIKE_PHOTO_RESPONSE = 578;

  public static final int VIEW_COMMENT_REQUEST = 579;
  public static final int VIEW_COMMENT_RESPONSE = 580;

  public static final int COMMENT_REQUEST = 581;

  public static final int LIKE_COMMENT_REQUEST = 582;
  public static final int LIKE_COMMENT_RESPONSE = 583;

  public static final int DELTE_PHOTO_REQUEST = 584;
  public static final int DELETE_PHOTO_RESPONSE = 585;

  public static final int UP_TO_HOT_ALBUM_REQUEST = 586;
  public static final int UP_TO_HOT_ALBUM_RESPONSE = 587;

  public static final int LIST_HOT_ALBUM_REQUEST = 588;
  public static final int LIST_HOT_ALBUM_RESPONSE = 589;

  public static final int DELETE_COMMENT_REQUEST = 591;
  public static final int DELETE_COMMENT_RESPONSE = 592;

  public static final int CHECK_PERMISSION_REQUEST = 593;
  public static final int PERMISSION_SUCCESS_RESPONSE = 594;
  public static final int PERMISSION_FAIL_RESPONSE = 595;

  public static final int CANCEL_REQUEST = 596;
  public static final int CANCEL_RESPONSE = 597;

  public static final int SEARCH_ALBUM_REQUEST = 598;
  public static final int SEARCH_ALBUM_RESPONSE = 599;

  public static final int MY_ALBUM_TYPE = 0;
  public static final int HOT_ALBUM_TYPE = 1;
  public static final int YOUR_ALBUM_TYPE = 2;
  private int ALBUM_TYPE = MY_ALBUM_TYPE;

  private static GameForm singleton;
  private ImageText text8;
  private ImageText text11;
  private int categoryIndex;
  private String type;
  private Hashtable logAction = null;
  private int currentAction;
  private int CATEGORY_IMAGE_HEIGHT;
  private int dy;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView;

  private Vector categories;
  private String photoId;

  private int packageNumber;
  private int totalPackage;
  private int percent;

  private GameMenu menuAlbum;
  private GameMenu menuAlbumEmpty;
  private GameMenu menuPhoto;
  private GameMenu menuViewPhoto;
  private GameMenu menuComment;
  private boolean isShowCreateAlbum;
  private boolean isShowChangeNameAlbum;
  private boolean isShowChangeRole;
  private CheckBoxArray cbRole;
  private TextField txtInput;

  private String albumId;

  private int photoIndex;
  private Category viewPhoto;
  private Category viewZoomPhoto;
  private int MAX_PHOTO_ON_A_ROW;

  private int VIEW_ZOOM_PHOTO_DY;
  private int VIEW_ZOOM_PHOTO_DX;

  private GameImage likeImage;
  private GameImage commentImage;

  private GameImage commentPhoto;
  private GameImageArray commentAlbumImage;

  private Vector comments;
  private int commentIndex;
  private int commentStart;
  private int commentEnd;

  private int albumStart;
  private int albumEnd;
  private int albumCurrentPage;
  private int albumTotalPage;

  private int photoStart;
  private int photoEnd;

  private TextField txtComment;
  private Sprite commentButtonSprite;
  private GameImage buttonImage;

  private GameImage[] arrowImage;

  private Hashtable _parameters;
  private String ofUser;
  private int currentX;

  private int totalRecord;

  private boolean isSeachAlbum;
  private String searchAlbumName;

  private GridMenu gridMenu;

  public static GameForm backForm;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmMyAlbum();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    this._parameters = parameters;
    categoryIndex = 0;
    photoIndex = 0;
    categories = new Vector();
    comments = new Vector();
    commentIndex = 0;
    commentStart = 0;
    commentEnd = 5;
    albumStart = 0;
    albumEnd = 10;
    albumCurrentPage = 1;
    albumTotalPage = 0;
    photoStart = 0;
    photoEnd = 10;
    logAction = new Hashtable();
    currentAction = 1;
    type = "category";
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    text11.setBold(true);
    CATEGORY_IMAGE_HEIGHT = 25;
    currentX = Global.getDefaultAvatar().getWidth() + 5;
    dy = DrawUtils.getTopBarHeight();
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    txtInput = new TextField(_manager, TextField.CONSTRAINT_ANY, null);
    txtInput.setSize(GameConstants.SCREEN_WIDTH - DEFAULT_TEXT_X * 2, text8.getHeight());
    txtInput.setAnchor(GameConstants.BOTTOM_LEFT_ANCHOR);
    txtInput.setPosition(DEFAULT_TEXT_X, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 5);
    txtInput.setVisible(false);

    txtComment = new TextField(_manager, TextField.CONSTRAINT_ANY, null);
    txtComment.setAnchor(GameConstants.BOTTOM_LEFT_ANCHOR);
    txtComment.setVisible(false);
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);
    commentButtonSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    commentButtonSprite.setImage(buttonImage);
    commentButtonSprite.setAnchor(Constants.TOP_LEFT_ANCHOR);
    commentButtonSprite.setVisible(false);
    commentButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        text8.drawString2(g, "Bình luận", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
      }
    });

    ALBUM_TYPE = NumberUtil.parseInt(parameters.get("albumType").toString());
    ofUser = (String) parameters.get("User");
    if (ofUser == null || ofUser.equals("")) {
      ofUser = Global.currentUser.getName();
    }
    if (ALBUM_TYPE == MY_ALBUM_TYPE || ALBUM_TYPE == YOUR_ALBUM_TYPE) {
      request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { ofUser, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
    } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
      request(LIST_HOT_ALBUM_REQUEST, new StringArray(new String[] { String.valueOf(albumStart), String.valueOf(albumEnd) },2));
    }
    // Create bottom bar
    if (ALBUM_TYPE == MY_ALBUM_TYPE) {
      menuAlbum = new GameMenu(null, new String[] { "Xem", "Xóa album", "Thay tên", "Tạo album", "Quyền xem", "Lên hot album", "Menu MXH" }, 7, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuPhoto = new GameMenu(null, new String[] { "Bình luận", "Xóa ảnh", "Thêm ảnh", "Tài khoản", "Menu MXH" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuComment = new GameMenu(null, new String[] { "Thích", "Tài khoản", "Kết bạn", "Xóa lời bình", "Menu MXH" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuAlbumEmpty = new GameMenu(null, new String[] { "Tạo album", "Menu MXH", "" }, 3, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
      menuAlbum = new GameMenu(null, new String[] { "Xem", "Tìm kiếm", "Menu MXH" }, 3, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuPhoto = new GameMenu(null, new String[] { "Bình luận", "Tài khoản", "Menu MXH" }, 3, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuComment = new GameMenu(null, new String[] { "Thích", "Tài khoản", "Kết bạn", "Menu MXH" }, 4, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    } else if (ALBUM_TYPE == YOUR_ALBUM_TYPE) {
      menuAlbum = new GameMenu(null, new String[] { "Xem", "Menu MXH" }, 2, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuPhoto = new GameMenu(null, new String[] { "Bình luận", "Xóa ảnh", "Thêm ảnh", "Tài khoản", "Menu MXH" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
      menuComment = new GameMenu(null, new String[] { "Thích", "Tài khoản", "Kết bạn", "Menu MXH" }, 4, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    }
    menuViewPhoto = new GameMenu(null, new String[] { "Bình luận", "Thích", "Menu MXH" }, 3, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    BottomBar bottomBar = DrawUtils.getBottomBar(_manager);
    bottomBar.setLabels("Menu", "Chọn", "");
    bottomBar.setLeftMenu("Menu", menuAlbum);
    _manager.enableTouchPad();

    cbRole = CheckBoxArray.create(3);
    String[] cbName = new String[] { "Chỉ mình tôi", "Bạn bè của tôi", "Tất cả mọi người" };
    for (int i = 0; i < 3; i++) {
      Checkbox cb = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE_APP, 0, 0);
      cb.setLabel(cbName[i]);
      cb.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
      cb.setVisible(false);
      cbRole.set(i, cb);
    }
    cbRole.array[2].setChecked(true);

    if (Constants.IS_240x320_SCREEN) {
      MAX_PHOTO_ON_A_ROW = 4;
    } else {
      MAX_PHOTO_ON_A_ROW = 5;
    }
    VIEW_ZOOM_PHOTO_DY = 0;
    VIEW_ZOOM_PHOTO_DX = 0;

    likeImage = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "like_icon.png");
    commentImage = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "comment_icon.png");

    arrowImage = new GameImage[4];
    // trai
    arrowImage[0] = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "arrow.png");
    // tren
    arrowImage[1] = ImageUtil.rotate(arrowImage[0], 90);
    // phai
    arrowImage[2] = ImageUtil.rotate(arrowImage[0], 180);
    // duoi
    arrowImage[3] = ImageUtil.rotate(arrowImage[0], 270);

    setTimerListener(this);

    // Manager manager, Image[] images, String[] titles, int numberOfItemPerRow, int dx, int dy, int hozDistance, int verDistance, EventListener eventListener
    gridMenu = new GridMenu(_manager, null, null, MAX_PHOTO_ON_A_ROW, 28, 55, 61, 61, this);
    gridMenu.setVisible(false);
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (type.equals("list_album")) {
      drawListAlbum(g);
    }
    if (isShowCreateAlbum || isShowChangeNameAlbum || isSeachAlbum) {
      drawCreateAndUpdateAlbum(g);
    }
    if (isShowChangeRole) {
      drawChangeRole(g);
    }
    if (type.equals("view_photo")) {
      drawViewPhoto(g);
    }
    if (type.equals("view_zoom_photo")) {
      drawViewZoomPhoto(g);
    }
    if (type.equals("view_comment")) {
      drawComment(g);
    }
    if (type.equals("view_comment_album")) {
      drawCommentAlbum(g);
    }
    drawMenu(g);
    if (!type.equals("view_zoom_photo")) {
      DrawUtils.drawTopBar(g);
    }
    if (type.equals("list_album")) {
      text8.drawString2(g, "Album: " + albumEnd + "/" + albumTotalPage, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (type.equals("list_photo")) {
      if (gridMenu != null) {
        text8.drawString2(g, "Ảnh:" + gridMenu.getNumberOfItem(), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
      }
    }
    if (type.equals("view_photo")) {
      if (gridMenu != null) {
        text8.drawString2(g, "<< " + (gridMenu.getCurrentSelectedIndex() + 1) + "/" + gridMenu.getNumberOfItem() + " >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
      }
    }
    if (type.equals("view_comment")) {
      g.drawImage(arrowImage[0], 0, 2, GameConstants.TOP_LEFT_ANCHOR);
      g.drawImage(arrowImage[2], GameConstants.SCREEN_WIDTH, 2, GameConstants.TOP_RIGHT_ANCHOR);
    }
  }

  private void drawCommentAlbum(Graphics g) {
    if (commentAlbumImage == null || commentAlbumImage.len() == 0) {
      return;
    }
    int commentDy = dy;
    int dx = 0;
    for (int i = 0; i < commentAlbumImage.len(); i++) {
      g.drawImage(commentAlbumImage.array[i], dx, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      // dx += commentAlbumImage[i].getWidth() + 5;
      dx += 55;
    }
    // commentDy = commentDy + commentAlbumImage[commentAlbumImage.length - 1].getHeight() + 10;
    commentDy = commentDy + 60;
    Category category = (Category) categories.elementAt(0);
    text8.setBold(true);
    text8.drawString2(g, (String) category.exParam.elementAt(0), GameColor.YELLOW_CODE, DEFAULT_TEXT_X, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    text8.setBold(false);
    commentDy += 25;
    for (int i = 0; i < comments.size(); i++) {
      Comment comment = (Comment) comments.elementAt(i);
      if (comment.comment == null || comment.comment.equals("")) {
        continue;
      }
      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy, GameConstants.SCREEN_WIDTH, commentDy);
      if (commentIndex == i) {
        g.setColor(0x53A4CF);
        g.fillRect(0, commentDy, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight());
      }
      GameImage avatar = Global.getAvatar(comment.userComment);
      g.drawImage(avatar, 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      text8.setBold(true);
      text8.drawString3(g, comment.userComment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      if (comment.like > 0) {
        g.drawImage(likeImage, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2, commentDy, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString3(g, String.valueOf(comment.like), GameColor.YELLOW_CODE, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2 + likeImage.getWidth() + 2, commentDy,
            GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      text8.setBold(false);
      commentDy = commentDy + 15;
      text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      commentDy = commentDy + 15;
      text8.drawString3(g, "[" + comment.created + "]", GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      commentDy = commentDy + 15;

      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy + 5, GameConstants.SCREEN_WIDTH, commentDy + 5);
      commentDy = commentDy + 7;
    }
    g.drawImage(Global.getAvatar(Global.currentUser.getName()), 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setSize(GameConstants.SCREEN_WIDTH - 65, text8.getHeight() * 2);
    txtComment.setPosition(Global.getDefaultAvatar().getWidth() + DEFAULT_TEXT_X, commentDy);
    commentDy = commentDy + txtComment.getHeight() + 7;
    commentButtonSprite.setPosition(GameConstants.SCREEN_WIDTH - 85, commentDy);
    commentButtonSprite.setVisible(true);
  }

  private void drawComment(Graphics g) {
    int commentDy = dy + 5;
    if (commentPhoto == null) {
      commentPhoto = Global.getDefaultAvatar();
    }
    g.drawImage(commentPhoto, GameConstants.SCREEN_WIDTH / 2, commentDy, GameConstants.TOP_HCENTER_ANCHOR);
    commentDy = commentDy + commentPhoto.getHeight() + 10;
    for (int i = 0; i < comments.size(); i++) {
      Comment comment = (Comment) comments.elementAt(i);
      if (comment.comment == null || comment.comment.equals("")) {
        continue;
      }
      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy, GameConstants.SCREEN_WIDTH, commentDy);
      if (commentIndex == i) {
        g.setColor(0x53A4CF);
        g.fillRect(0, commentDy, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight());
      }
      GameImage avatar = Global.getAvatar(comment.userComment);
      g.drawImage(avatar, 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      text8.setBold(true);
      text8.drawString3(g, comment.userComment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      if (comment.like > 0) {
        g.drawImage(likeImage, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2, commentDy, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString3(g, String.valueOf(comment.like), GameColor.YELLOW_CODE, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2 + likeImage.getWidth() + 2, commentDy,
            GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      text8.setBold(false);
      commentDy = commentDy + 15;
      if (commentIndex == i) {
        if (text8.stringWidth(comment.comment) > GameConstants.SCREEN_WIDTH - Global.getDefaultAvatar().getWidth() + 5) {
          text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, currentX, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          g.drawImage(avatar, 0, commentDy - 15, GameConstants.TOP_LEFT_ANCHOR);
        } else {
          text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        }
      } else {
        text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      commentDy = commentDy + 15;
      text8.drawString3(g, "[" + comment.created + "]", GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      commentDy = commentDy + 15;

      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy + 5, GameConstants.SCREEN_WIDTH, commentDy + 5);
      commentDy = commentDy + 7;
    }
    g.drawImage(Global.getAvatar(Global.currentUser.getName()), 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setSize(GameConstants.SCREEN_WIDTH - 65, text8.getHeight() * 2);
    txtComment.setPosition(Global.getDefaultAvatar().getWidth() + DEFAULT_TEXT_X, commentDy);
    commentDy = commentDy + txtComment.getHeight() + 7;
    commentButtonSprite.setPosition(GameConstants.SCREEN_WIDTH - 85, commentDy);
    commentButtonSprite.setVisible(true);
  }

  private void drawListAlbum(Graphics g) {
    int textY = dy;
    int index = 0;
    if (categoryIndex == 0) {
      dy = DrawUtils.getTopBarHeight();
    }
    if (categories == null || categories.isEmpty()) {
      text8.drawString2(g, "Không có album nào", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      if (categoryIndex == index) {
        g.setColor(0x53A4CF);
        g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight());
      }
      g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString3(g, category.name, GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      // Số ảnh trong album
      if (type.equals("list_album")) {
        text8.drawString3(g, (String) category.exParam.elementAt(0), GameColor.YELLOW_CODE, category.image.getWidth() + 7 + text8.stringWidth(category.name), textY + category.image.getHeight() / 50,
            GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        textY = textY + 16;
      }
      // like
      g.drawImage(likeImage, category.image.getWidth() + 7, textY, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, (String) category.exParam.elementAt(2), GameColor.YELLOW_CODE, category.image.getWidth() + 7 + likeImage.getWidth() + 2, textY, GameConstants.TOP_LEFT_ANCHOR);
      // comment
      g.drawImage(commentImage, category.image.getWidth() + 7 + likeImage.getWidth() + 2 + text8.stringWidth((String) category.exParam.elementAt(2)) + 5, textY + 2, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, (String) category.exParam.elementAt(3), GameColor.YELLOW_CODE, category.image.getWidth() + 7 + likeImage.getWidth() + 2
          + text8.stringWidth((String) category.exParam.elementAt(2)) + commentImage.getWidth() + 12, textY, GameConstants.TOP_LEFT_ANCHOR);
      // Ngày tạo album
      textY = textY + 17;
      text8.drawString3(g, (String) category.exParam.elementAt(1), GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 18;
      g.setColor(0xC0C0C0);
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      index++;
    }
    text8.drawString3(g, "", GameColor.WHITE_CODE, 0, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    scrollBar.draw(g);
    if (percent > 0 && percent < 100) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(percent + "%");
    } else {
      DrawUtils.getBottomBar(_manager).setCenterLabel("Chọn");
    }
  }

  private void drawCreateAndUpdateAlbum(Graphics g) {
    g.setColor(0xA9A9A9);
    g.fillRect(0, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40, GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40);
    g.drawRect(0, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40, GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40);
    text8.drawString2(g, "Nhập tên album:", GameColor.WHITE_CODE, 5, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 25, GameConstants.BOTTOM_LEFT_ANCHOR);
    txtInput.draw(g);
  }

  private void drawChangeRole(Graphics g) {
    dy = DrawUtils.getTopBarHeight();
    text8.drawString2(g, "Quyền xem album:Ảnh", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
    int textY = dy;
    textY = text8.drawParagraph2(g, "Những ai có quyền xem và bình luận album này:", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH, DEFAULT_TEXT_X, textY, scrollBar);
    textY = textY + 5;
    for (int i = 0; i < cbRole.len(); i++) {
      if (categoryIndex == i) {
        cbRole.array[i].setFocused(true);
      } else {
        cbRole.array[i].setFocused(false);
      }
      cbRole.array[i].setVisible(true);
      cbRole.array[i].setPosition(DEFAULT_TEXT_X, textY);
      cbRole.array[i].draw(g);
      textY = textY + 20;
    }
  }

  private void drawViewZoomPhoto(Graphics g) {
    if (viewZoomPhoto != null) {
      g.drawImage(viewZoomPhoto.image, VIEW_ZOOM_PHOTO_DX, VIEW_ZOOM_PHOTO_DY, GameConstants.TOP_LEFT_ANCHOR);
      g.drawImage(arrowImage[0], 0, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_LEFT_ANCHOR);
      g.drawImage(arrowImage[1], GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_LEFT_ANCHOR);
      g.drawImage(arrowImage[2], GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_RIGHT_ANCHOR);
      g.drawImage(arrowImage[3], GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight(), GameConstants.BOTTOM_LEFT_ANCHOR);
    }
  }

  private void drawViewPhoto(Graphics g) {
    int textY = dy;
    if (viewPhoto == null) {
      return;
    }
    if (viewPhoto.image != null) {
      g.drawImage(viewPhoto.image, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    }
    text11.setBold(true);
    textY = dy + 2;
    g.drawImage(likeImage, 5, textY, GameConstants.TOP_HCENTER_ANCHOR);
    if (viewPhoto.exParam != null && !viewPhoto.exParam.isEmpty()) {
      text11.drawString2(g, (String) viewPhoto.exParam.elementAt(0), GameColor.YELLOW_CODE, likeImage.getWidth() + 3, textY, GameConstants.TOP_LEFT_ANCHOR);
      g.drawImage(commentImage, 0, textY + likeImage.getHeight() + 2, GameConstants.TOP_LEFT_ANCHOR);
      text11.drawString2(g, (String) viewPhoto.exParam.elementAt(1), GameColor.YELLOW_CODE, likeImage.getWidth() + 2, textY + likeImage.getHeight() + 1, GameConstants.TOP_LEFT_ANCHOR);
    }
  }

  private void drawMenu(Graphics g) {
    if (percent > 0 && percent < 100) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(percent + "%");
    }
    if (isShowCreateAlbum || isShowChangeNameAlbum || isSeachAlbum) {
      DrawUtils.getBottomBar(_manager).setLabels("Đóng", "Đồng ý", "Xóa");
    } else {
      if (!isLoadingCompleted()) {
        DrawUtils.getBottomBar(_manager).setRightLabel("Dừng tải");
      } else {
        if (type.equals("list_album")) {
          if (ALBUM_TYPE == MY_ALBUM_TYPE) {
            if (categories.isEmpty()) {
              DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuAlbumEmpty);
            } else {
              DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuAlbum);
            }
          } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
            DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuAlbum);
          }
        } else if (type.equals("list_photo")) {
          DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuPhoto);
          DrawUtils.getBottomBar(_manager).setCenterLabel("");
        } else if (type.equals("view_photo")) {
          DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuViewPhoto);
          DrawUtils.getBottomBar(_manager).setCenterLabel("Zoom");
          DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
        } else if (type.equals("view_zoom_photo")) {
          DrawUtils.getBottomBar(_manager).setLeftMenu(null, null);
          DrawUtils.getBottomBar(_manager).setLabels(null, null, "Đóng");
        } else if (type.equals("view_comment") || type.equals("view_comment_album")) {
          DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuComment);
          DrawUtils.getBottomBar(_manager).setCenterLabel(null);
          if (txtComment.isFocused()) {
            DrawUtils.getBottomBar(_manager).setRightLabel("Xóa");
          } else {
            DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
          }
        } else {
          DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
        }
      }
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    if (header == CANCEL_RESPONSE) {
      packageNumber = totalPackage;
      return;
    }
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    if (!type.equals("view_photo") && !type.equals("view_zoom_photo") && !type.equals("view_comment") && !type.equals("list_photo") && !type.equals("view_comment_album")) {
      photoIndex = 0;
      categoryIndex = 0;
    }
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case PERMISSION_FAIL_RESPONSE:
      Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Bạn không có quyền", "xem album này" ));
      break;
    case PERMISSION_SUCCESS_RESPONSE:
      String id = mapDataPackage.getString("id");
      int requestType = mapDataPackage.getInt("nextRequestHeader");
      if (requestType == LIST_PHOTO_REQUEST) {
        albumStart = 0;
        albumEnd = 10;
      }
      request(requestType, new StringArray(new String[] { id, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
      clearCategory();
      break;
    case CREATED_ALBUM_RESPONSE:
      isShowCreateAlbum = false;
      isShowChangeNameAlbum = false;
      txtInput.setVisible(false);
      txtInput.clearText();
      categoryIndex = 0;
      
      // Start picture import
      Platform platform = Platform.getInstance();
      platform.addPictureImportEventHandler(this);
      platform.startPictureImport();
      break;
    case LIST_HOT_ALBUM_RESPONSE:
    case LIST_MY_ALBUM_RESPONSE:
      isShowCreateAlbum = false;
      isShowChangeNameAlbum = false;
      isSeachAlbum = false;
      txtInput.setVisible(false);
      txtInput.clearText();
      if (Category.ERROR == mapDataPackage.getInt("errorCode")) {
        if (Global.currentUser.getName().equals(ofUser) && ALBUM_TYPE == MY_ALBUM_TYPE) {
          Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Bạn chưa có album nào", "Bạn có muốn tạo album không?" ), 20);
        }
        return;
      }
      Category category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("caption");
      category.name = category.code;
      category.parent = mapDataPackage.getString("parent");
      category.user = mapDataPackage.getString("user");
      category.status = mapDataPackage.getInt("status");
      category.totalRecord = NumberUtil.parseInt(mapDataPackage.getString("total_album"));
      totalRecord = category.totalRecord;
      category.user = mapDataPackage.getString("user");
      ByteArray btImage = mapDataPackage.getByteArray("source");
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      category.exParam.addElement(mapDataPackage.getString("child"));
      category.exParam.addElement(mapDataPackage.getString("created"));
      category.exParam.addElement(mapDataPackage.getString("like"));
      category.exParam.addElement(mapDataPackage.getString("comment"));
      CATEGORY_IMAGE_HEIGHT = 50;
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      albumTotalPage = category.totalRecord;
      categories.addElement(category);
      break;
    case CHANGE_ALBUM_NAME_RESPONSE:
      String newName = mapDataPackage.getString("new_name");
      category = (Category) categories.elementAt(categoryIndex);
      category.code = newName;
      category.name = newName;
      break;
    case UP_TO_HOT_ALBUM_RESPONSE:
      Global.alert.showAlert(this, GameAlert.OK_TYPE, "Lên HOT album thành công");
      break;
    case LIST_PHOTO_RESPONSE:
      category = new Category();
      category.status = mapDataPackage.getInt("errorCode");
      category.parent = mapDataPackage.getString("parent");
      category.exParam.addElement(mapDataPackage.getString("albumName"));
      // Tổng số photo trong album
      category.totalRecord = NumberUtil.parseInt(mapDataPackage.getString("total_photo"));
      if (category.status != Category.ERROR) {
        category.id = mapDataPackage.getString("id");
        btImage = mapDataPackage.getByteArray("source");
        category.image = ImageUtil.resizeImage2(GameImage.createImage(btImage, 0, btImage.len()), 60, 60);
        category.user = mapDataPackage.getString("user");
        packageNumber = mapDataPackage.getInt("packageNumber");
        totalPackage = mapDataPackage.getInt("totalPackage");
        percent = (packageNumber * 100) / totalPackage;
        // Danh sach id cua photo
        if (gridMenu.getNumberOfItem() < category.totalRecord) {
          gridMenu.addImageItem(category.image, category.id);
        }
        gridMenu.setVisible(true);
        categories.addElement(category);
      }
      DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuPhoto);
      break;
    case VIEW_PHOTO_RESPONSE:
      viewPhoto = new Category();
      btImage = mapDataPackage.getByteArray("image");
      viewPhoto.image = ImageUtil.resizeImage2(GameImage.createImage(btImage, 0, btImage.len()), 240, 320);
      viewPhoto.name = mapDataPackage.getString("caption");
      viewPhoto.parent = mapDataPackage.getString("parent");
      viewPhoto.exParam.addElement(String.valueOf(mapDataPackage.getInt("like")));
      viewPhoto.exParam.addElement(String.valueOf(mapDataPackage.getInt("comment")));
      DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuViewPhoto);
      gridMenu.setVisible(false);
      break;
    case VIEW_ZOOM_PHOTO_RESPONSE:
      viewZoomPhoto = new Category();
      btImage = mapDataPackage.getByteArray("image");
      viewZoomPhoto.image = GameImage.createImage(btImage, 0, btImage.len());
      viewZoomPhoto.name = mapDataPackage.getString("caption");
      viewZoomPhoto.parent = mapDataPackage.getString("parent");
      gridMenu.setVisible(false);
      break;
    case LIKE_PHOTO_RESPONSE:
      int errorCode = mapDataPackage.getInt("errorCode");
      if (errorCode == Category.ERROR) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn đã like ảnh này rồi");
        return;
      }
      if (viewPhoto != null) {
        viewPhoto.exParam.setElementAt(mapDataPackage.getString("like"), 0);
      }
      break;
    case VIEW_COMMENT_RESPONSE:
      commentIndex = 0;
      dy = DrawUtils.getTopBarHeight() + 5;
      txtComment.clearText();
      txtComment.setVisible(true);
      CATEGORY_IMAGE_HEIGHT = 50;
      if (type.equals("view_comment_album")) {
        commentAlbumImage = GameImageArray.create(categories.size());
        for (int i = 0; i < commentAlbumImage.len(); i++) {
          commentAlbumImage.array[i] = ((Category) categories.elementAt(i)).image;
        }
      } else if (type.equals("view_comment")) {
        if (commentPhoto == null) {
          commentPhoto = ImageUtil.resizeImage1(viewPhoto.image, 0.4f, 0, 0, false);
        }
      }
      if (mapDataPackage.getSize() <= 1) {
        return;
      }
      Comment comment = new Comment();
      comment.id = mapDataPackage.getString("commentId");
      comment.userComment = mapDataPackage.getString("user_comment");
      comment.comment = mapDataPackage.getString("message");
      comment.created = mapDataPackage.getString("created");
      comment.totalComment = mapDataPackage.getInt("total_comment");
      comment.like = mapDataPackage.getInt("like_comment");
      comments.addElement(comment);
      break;
    case LIKE_COMMENT_RESPONSE:
      errorCode = mapDataPackage.getInt("errorCode");
      if (errorCode == Category.ERROR) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn đã like lời bình này rồi");
        return;
      }
      comment = (Comment) comments.elementAt(commentIndex);
      if (comment != null) {
        comment.like = mapDataPackage.getInt("like");
      }
      break;
    case DELETE_PHOTO_RESPONSE:
      gridMenu.removeItem(gridMenu.getCurrentSelectedIndex());
      categories.removeElementAt(categoryIndex);
      break;
    case DELETE_ALBUM_RESPONSE:
      categories.removeElementAt(categoryIndex);
      break;
    case DELETE_COMMENT_RESPONSE:
      comments.removeElementAt(commentIndex);
      break;
    }
  }

  private String buildLogAction(int requestType, StringArray parameters) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters.len(); i++) {
      sb.append(parameters.array[i]);
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.RIGHT:
      if (type.equals("view_zoom_photo")) {
        VIEW_ZOOM_PHOTO_DX = VIEW_ZOOM_PHOTO_DX - 10;
      }
      if (type.equals("view_photo")) {
        if (gridMenu.getCurrentSelectedIndex() < gridMenu.getNumberOfItem() - 1) {
          gridMenu.setCurrentSelectedIndex(gridMenu.getCurrentSelectedIndex() + 1);
          DataPackage dataPackage = DataPackage.createDataPackage1(VIEW_PHOTO_REQUEST);
          dataPackage.putString(gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
          dataPackage.putInt(0);// Khong zoom
          Global.appClient.write(dataPackage);
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          viewZoomPhoto = null;
        }
      }
      if (type.equals("list_photo")) {
        if (photoIndex < categories.size() - 1) {
          photoIndex++;
        }
      }
      if (type.equals("view_comment")) {
        Comment comment = (Comment) comments.elementAt(0);
        if (commentEnd >= comment.totalComment) {
          return;
        }
        if ((commentEnd + 5) > comment.totalComment) {
          commentEnd = comment.totalComment;
          commentStart = commentEnd - 5;
        } else {
          commentStart += 5;
          commentEnd += 5;
        }
        request(VIEW_COMMENT_REQUEST, new StringArray(new String[] { gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()), String.valueOf(commentStart), String.valueOf(commentEnd) },3));
        commentIndex = 0;
        if (comments != null) {
          comments.removeAllElements();
        }
      }
      if (type.equals("list_album")) {
        if (categories.isEmpty()) {
          return;
        }
        Category category = (Category) categories.elementAt(0);
        if (albumEnd >= category.totalRecord) {
          return;
        }
        if ((albumEnd + 10) > category.totalRecord) {
          albumEnd = category.totalRecord;
          albumStart = albumEnd - 10;
        } else {
          albumStart += 10;
          albumEnd += 10;
        }
        if (isSeachAlbum) {
          request(SEARCH_ALBUM_REQUEST, new StringArray(new String[] { "", String.valueOf(albumStart), String.valueOf(albumEnd) },3));
        } else {
          if (ALBUM_TYPE == MY_ALBUM_TYPE || ALBUM_TYPE == YOUR_ALBUM_TYPE) {
            request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { ofUser, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
          } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
            request(LIST_HOT_ALBUM_REQUEST, new StringArray(new String[] { String.valueOf(albumStart), String.valueOf(albumEnd) },2));
          }
        }
        clearCategory();
      }
      break;
    case Key.LEFT:
      if (type.equals("view_zoom_photo")) {
        VIEW_ZOOM_PHOTO_DX = VIEW_ZOOM_PHOTO_DX + 10;
      }
      if (type.equals("view_photo")) {
        if (gridMenu.getCurrentSelectedIndex() > 0) {
          gridMenu.setCurrentSelectedIndex(gridMenu.getCurrentSelectedIndex() - 1);
          DataPackage dataPackage = DataPackage.createDataPackage1(VIEW_PHOTO_REQUEST);
          dataPackage.putString(gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
          dataPackage.putInt(0);// Khong zoom
          Global.appClient.write(dataPackage);
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          viewZoomPhoto = null;
        }
      }
      if (type.equals("list_photo")) {
        if (photoIndex > 0) {
          photoIndex--;
        }
      }
      if (type.equals("view_comment")) {
        if (commentStart <= 0) {
          return;
        }
        commentStart -= 5;
        commentEnd -= 5;
        if (commentStart < 0) {
          commentStart = 0;
          commentEnd = 5;
        }
        request(VIEW_COMMENT_REQUEST, new StringArray(new String[] { gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()), String.valueOf(commentStart), String.valueOf(commentEnd) },3));
        commentIndex = 0;
        if (comments != null) {
          comments.removeAllElements();
        }
      }
      if (type.equals("list_album")) {
        if (albumStart <= 0) {
          return;
        }
        if (albumEnd >= totalRecord) {
          if ((albumEnd - albumStart) < 10) {
            albumStart -= 10;
          } else {
            albumStart -= 10;
            albumEnd -= 10;
          }
        } else {
          albumStart -= 10;
          albumEnd -= 10;
        }
        if (albumStart <= 0) {
          albumStart = 0;
          albumEnd = 10;
        }
        if (isSeachAlbum) {
          request(SEARCH_ALBUM_REQUEST, new StringArray(new String[] { "", String.valueOf(albumStart), String.valueOf(albumEnd) },3));
        } else {
          if (ALBUM_TYPE == MY_ALBUM_TYPE || ALBUM_TYPE == YOUR_ALBUM_TYPE) {
            request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { ofUser, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
          } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
            request(LIST_HOT_ALBUM_REQUEST, new StringArray(new String[] { String.valueOf(albumStart), String.valueOf(albumEnd) },2));
          }
        }
        clearCategory();
      }
      break;
    case Key.DOWN:
      if (type.equals("view_comment") || type.equals("view_comment_album")) {
        if (commentIndex < comments.size() + 1) {
          commentIndex++;
          dy = dy - 50;
        }
        if (commentIndex != comments.size() + 1) {
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Bình luận", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else if (commentIndex == comments.size() + 1) {
          txtComment.setFocused(false);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Bình luận", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
        if (commentIndex == comments.size()) {
          txtComment.setFocused(true);
        } else {
          txtComment.setFocused(false);
        }
      }
      if (type.equals("view_zoom_photo")) {
        VIEW_ZOOM_PHOTO_DY = VIEW_ZOOM_PHOTO_DY - 10;
      }
      if (type.equals("list_album")) {
        if (categoryIndex < categories.size() - 1) {
          categoryIndex++;
        }
      }
      if (type.equals("list_album")) {
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT);
        }
      }
      if (type.equals("list_photo")) {
        Category category = (Category) categories.elementAt(0);
        if (gridMenu.getNumberOfItem() < category.totalRecord) {
          photoStart = photoEnd;
          photoEnd += MAX_PHOTO_ON_A_ROW;
          if (photoEnd > category.totalRecord) {
            photoStart = category.totalRecord - gridMenu.getNumberOfItem();
            photoEnd = category.totalRecord;
          }
          request(LIST_PHOTO_REQUEST, new StringArray(new String[] { category.parent, String.valueOf(photoStart), String.valueOf(photoEnd) },3));
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        }
      }
      if (isShowChangeRole) {
        if (categoryIndex < cbRole.len() - 1) {
          categoryIndex++;
        }
      }
      break;
    case Key.UP:
      if (type.equals("view_comment") || type.equals("view_comment_album")) {
        if (commentIndex > 0) {
          commentIndex--;
          dy = dy + 50;
        }
        if (commentIndex != comments.size() + 1) {
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Bình luận", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else if (commentIndex == comments.size() + 1) {
          txtComment.setFocused(false);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Bình luận", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
        if (commentIndex == comments.size()) {
          txtComment.setFocused(true);
        } else {
          txtComment.setFocused(false);
        }
      }
      if (type.equals("view_zoom_photo")) {
        VIEW_ZOOM_PHOTO_DY = VIEW_ZOOM_PHOTO_DY + 10;
      }
      if (type.equals("list_album")) {
        if (categoryIndex > 0) {
          categoryIndex--;
        } else if (categoryIndex == 0) {
        }
      }
      if (type.equals("list_album")) {
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT);
        }
      }
      if (type.equals("list_photo")) {
        if (photoIndex > 0) {
          photoIndex = (photoIndex - MAX_PHOTO_ON_A_ROW < 0) ? photoIndex : photoIndex - MAX_PHOTO_ON_A_ROW;
        }
      }
      if (isShowChangeRole) {
        if (categoryIndex > 0) {
          categoryIndex--;
        }
      }
      if (type.equals("create_album")) {
        if (categoryIndex > 0) {
          categoryIndex--;
        }
      }
      break;
    case Key.FIRE:
      currentAction++;
      dy = DrawUtils.getTopBarHeight();
      if (txtInput.isFocused() && txtInput.getText().length() == 0) {
        txtInput.pointerReleased(txtInput, txtInput.getRealX(), txtInput.getRealY());
      }
      if (txtComment.isFocused()) {
        txtComment.pointerReleased(txtComment, txtComment.getRealX(), txtComment.getRealY());
      }
      if (isShowCreateAlbum) {
    	if(txtInput.getText().length() == 0){
    		Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập tên album");
    		return;
    	}
        request(CREATED_ALBUM_REQUEST, txtInput.getText());
        clearCategory();
      } else if (isShowChangeNameAlbum) {
        Category category = (Category) categories.elementAt(categoryIndex);
        request(CHANGE_ALBUM_NAME_REQUEST, new StringArray(new String[] { category.id, txtInput.getText() },2));
      } else if (isSeachAlbum) {
        searchAlbumName = txtInput.getText();
        request(LIST_HOT_ALBUM_REQUEST, new StringArray(new String[] { searchAlbumName, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
        clearCategory();
      } else if (isShowChangeRole) {
        if (cbRole.array[categoryIndex].isChecked()) {
          return;
        }
        for (int i = 0; i < cbRole.len(); i++) {
          cbRole.array[i].setChecked(false);
        }
        cbRole.array[categoryIndex].setChecked(true);
        DataPackage dataPackage = DataPackage.createDataPackage1(CHANGE_ROLE_REQUEST);
        dataPackage.putString(photoId);
        dataPackage.putString(cbRole.array[categoryIndex].getLabel());
        Global.appClient.write(dataPackage);
      }else if (type.equals("list_album")) {
        Category category = (Category) categories.elementAt(categoryIndex);
        request(CHECK_PERMISSION_REQUEST, new StringArray(new String[] { category.id, type, String.valueOf(LIST_PHOTO_REQUEST) },3));
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      } else if (type.equals("list_photo")) {
        if (!isLoadingCompleted()) {
          return;
        }
        DataPackage dataPackage = DataPackage.createDataPackage1(VIEW_PHOTO_REQUEST);
        dataPackage.putString(gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
        dataPackage.putInt(0);// Khong zoom
        Global.appClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        if (gridMenu != null) {
          gridMenu.setVisible(false);
        }
      } else if (type.equals("view_photo")) {
        DataPackage dataPackage = DataPackage.createDataPackage1(VIEW_PHOTO_REQUEST);
        dataPackage.putString(gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
        dataPackage.putInt(1);// Zoom
        Global.appClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      } else if (type.equals("view_comment") || type.equals("view_comment_album")) {
        if (commentIndex == comments.size() + 1) {
          if (txtComment.getText().length() == 0) {
            Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa viết bình luận");
            return;
          }
          if (type.equals("view_comment")) {
            request(COMMENT_REQUEST, new StringArray(new String[] { gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()), txtComment.getText() },2));
          } else if (type.equals("view_comment_album")) {
            request(COMMENT_REQUEST, new StringArray(new String[] { ((Category) categories.elementAt(0)).parent, txtComment.getText() },2));
          }
          if (comments != null) {
            comments.removeAllElements();
          }
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        }
      }
      break;
    case Key.SOFT_LEFT:
      if (isShowCreateAlbum || isShowChangeNameAlbum || isSeachAlbum) {
        txtInput.setVisible(false);
        isShowCreateAlbum = false;
        isShowChangeNameAlbum = false;
        isSeachAlbum = false;
        txtInput.clearText();
      }
      break;
    case Key.SOFT_RIGHT:
      if (!type.equals("list_photo") && !type.equals("view_photo") && !type.equals("view_zoom_photo") && !type.equals("view_comment") && !type.equals("view_comment_album")) {
        commentAlbumImage = null;
      }
      if (isShowCreateAlbum || isShowChangeNameAlbum || isSeachAlbum) {
        txtInput.deleteLastChar();
        return;
      }
      if (isShowChangeRole) {
        for (int i = 0; i < cbRole.len(); i++) {
          cbRole.array[i].setVisible(false);
        }
        isShowChangeRole = false;
        categoryIndex = 0;
        type = "list_album";
        return;
      }
      if (type.equals("create_album")) {
        albumStart = 0;
        albumEnd = 10;
        request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { ofUser, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
        isShowChangeRole = false;
        txtInput.setVisible(false);
        txtInput.setFocused(false);
        clearCategory();
        return;
      }
      if (type.equals("list_album")) {
        if (backForm != null) {
          Global.nextState(backForm, _parameters);
          if (backForm instanceof FrmGroup18Plus) {
            FrmGroup18Plus.setTab(1);
          } else if (backForm instanceof FrmGroupKetBanMangXHChat) {
            FrmGroupKetBanMangXHChat.setTab(1);
          }
        } else {
          if (Global.systemCanvas.lastState instanceof FrmDownloadResource) {
            GameGlobal.nextState(FrmGroupMenu.instance(), null);
          } else {
            GameGlobal.nextState(Global.systemCanvas.lastState, _parameters);
          }
        }
      } else if (type.equals("list_photo")) {
        if (ALBUM_TYPE == MY_ALBUM_TYPE || ALBUM_TYPE == YOUR_ALBUM_TYPE) {
          request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { ofUser, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
        } else if (ALBUM_TYPE == HOT_ALBUM_TYPE) {
          request(LIST_HOT_ALBUM_REQUEST, new StringArray(new String[] { String.valueOf(albumStart), String.valueOf(albumEnd) },2));
        }
        photoIndex = 0;
        categoryIndex = 0;
        photoStart = 0;
        photoEnd = 10;
        clearCategory();
        gridMenu.clearData();
        gridMenu.setVisible(false);
      } else if (type.equals("view_photo")) {
        photoIndex = 0;
        dy = DrawUtils.getTopBarHeight();
        type = "list_photo";
        viewPhoto = null;
        viewZoomPhoto = null;
        if (gridMenu != null) {
          gridMenu.setVisible(true);
        }
      } else if (type.equals("view_zoom_photo")) {
        VIEW_ZOOM_PHOTO_DX = 0;
        VIEW_ZOOM_PHOTO_DY = 0;
        type = "view_photo";
      } else if (type.equals("view_comment") || type.equals("view_comment_album")) {
        if (txtComment.isFocused()) {
          txtComment.deleteLastChar();
        } else {
          commentAlbumImage = null;
          commentPhoto = null;
          if (comments != null) {
            comments.removeAllElements();
          }
          dy = DrawUtils.getTopBarHeight();
          if (type.equals("view_comment")) {
            type = "view_photo";
          } else if (type.equals("view_comment_album")) {
            type = "list_photo";
            gridMenu.setVisible(true);
          }
          txtComment.setVisible(false);
          commentButtonSprite.setVisible(false);
          commentIndex = 0;
          commentStart = 0;
          commentEnd = 5;
        }
      }
      break;
    default:
      if (isShowCreateAlbum || isShowChangeNameAlbum || isSeachAlbum) {
        txtInput.keyReleased1(keyCode);
      }
      if (txtComment.isFocused()) {
        txtComment.keyReleased1(keyCode);
      }
      break;
    }
  }

  // TODO: đang chưa làm được multiupload và lấy được tên file ảnh khi import ảnh
  public void onPlatformPictureImport(Platform platform, PlatformPictureImportEvent event) {
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang up ảnh...", 99);
    platform.removePictureImportEventHandler(this);
    ByteBuffer byteBuffer = new ByteBuffer();
    event.picture.toBuffer(byteBuffer, Image.FormatPNG);
    ByteArray data = ByteArray.create(byteBuffer.getLength());
    for (int i = 0; i < data.len(); i++) {
      data.set(i, byteBuffer.getByte(i));
    }
    
    DataPackage dataPackage = DataPackage.createDataPackage3(CREATE_PHOTO_REQUEST, data.len() + 150);
    dataPackage.putString(albumId);
    dataPackage.putString("Không tên");
    dataPackage.putByteArray(data);
    Global.appClient.write(dataPackage);
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 20 && eventType == GameAlert.YES_BUTTON) {
      isShowCreateAlbum = true;
      txtInput.setVisible(true);
      txtInput.setFocused(true);
    }
    if (alertId == 100 && eventType == GameAlert.YES_BUTTON) {
      FrmGroupNapXuAndExchangeGold.backForm = this;
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), null);
    }
    if (alertId == 10 && eventType == GameAlert.YES_BUTTON) {
      Category category = (Category) categories.elementAt(categoryIndex);
      request(DELTE_ALBUM_REQUEST, category.id);
    }
    if (alertId == 11 && eventType == GameAlert.YES_BUTTON) {
      request(DELTE_PHOTO_REQUEST, gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
    }
    if (alertId == 12 && eventType == GameAlert.YES_BUTTON) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      request(DELETE_COMMENT_REQUEST, comment.id);
    }
  }

  private boolean isLoadingCompleted() {
    return packageNumber == totalPackage;
  }

  private void clearCategory() {
    categories.removeAllElements();
    categoryIndex = 0;
    photoIndex = 0;
    dy = DrawUtils.getTopBarHeight();
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
  }

  private void request(int header, StringArray parameters) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters.len(); i++) {
      dataPackage.putString(parameters.array[i]);
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters));
  }

  private void request(int header, String param) {
    request(header, new StringArray(new String[] { param },1));
  }

  public void destroy() {
    text8 = null;
    categoryIndex = 0;
    type = null;
    logAction = null;
    currentAction = 1;
    CATEGORY_IMAGE_HEIGHT = 0;
    dy = 0;
    scrollBar = null;
    textView = null;
    categories = null;
    packageNumber = 0;
    totalPackage = 0;
    percent = 0;
    txtInput = null;
    isShowCreateAlbum = false;
    isShowChangeNameAlbum = false;
    isShowChangeRole = false;
    menuAlbum = null;
    menuPhoto = null;
    cbRole = null;
    photoId = null;
    albumId = null;
    viewPhoto = null;
    viewZoomPhoto = null;
    likeImage = null;
    commentImage = null;
    comments = null;
    commentPhoto = null;
    commentButtonSprite = null;
    buttonImage = null;
    commentIndex = 0;
    commentStart = 0;
    commentEnd = 5;
    photoStart = 0;
    photoEnd = 10;
    arrowImage = null;
    menuComment = null;
    albumStart = 0;
    albumEnd = 10;
    commentAlbumImage = null;
    _parameters = null;
    ofUser = null;
    gridMenu = null;
    menuAlbumEmpty = null;
  }

  public void onActionPerform(Event event) {
    // "Xem", "Xóa album", "Thay tên", "Tạo album", "Quyền xem",
    // "Lên hot album", "Menu MXH"
    String action = event.getAction();
    if (action.equals("Menu MXH")) {
      if (backForm != null) {
        Global.nextState(backForm, _parameters);
        if (backForm instanceof FrmGroup18Plus) {
          FrmGroup18Plus.setTab(1);
        } else if (backForm instanceof FrmGroupKetBanMangXHChat) {
          FrmGroupKetBanMangXHChat.setTab(1);
        }
      } else {
        if (Global.systemCanvas.lastState instanceof FrmDownloadResource) {
          GameGlobal.nextState(FrmGroupMenu.instance(), null);
        } else {
          GameGlobal.nextState(Global.systemCanvas.lastState, null);
        }
      }
    } else if (action.equals("Tạo album")) {
      isShowCreateAlbum = true;
      txtInput.setVisible(true);
      txtInput.setFocused(true);
    } else if (action.equals("Xóa album")) {
      Global.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có chắc chắn xóa album này", 10);
    } else if (action.equals("Thay tên")) {
      isShowChangeNameAlbum = true;
      txtInput.setVisible(true);
      txtInput.setFocused(true);
    } else if (action.equals("Quyền xem")) {
      isShowChangeRole = true;
      type = "change_role";
      Category category = (Category) categories.elementAt(categoryIndex);
      photoId = category.id;
      categoryIndex = cbRole.len() - 1;
    } else if (action.equals("Xem")) {
      Category category = (Category) categories.elementAt(categoryIndex);
      request(CHECK_PERMISSION_REQUEST, new StringArray(new String[] { category.id, type, String.valueOf(LIST_PHOTO_REQUEST) },3));
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    } else if (action.equals("Lên hot album")) {
      Category category = (Category) categories.elementAt(categoryIndex);
      request(UP_TO_HOT_ALBUM_REQUEST, category.id);
    }
    // "Bình luận", "Xóa ảnh", "Thêm ảnh", "Tài khoản","Menu MXH"
    else if (action.equals("Bình luận") && type.equals("list_photo")) {
      Category category = (Category) categories.elementAt(0);
      request(VIEW_COMMENT_REQUEST, new StringArray(new String[] { category.parent, String.valueOf(commentStart), String.valueOf(commentEnd) },3));
      commentIndex = 0;
      if (comments != null) {
        comments.removeAllElements();
      }
      gridMenu.setVisible(false);
    } else if (action.equals("Xóa ảnh")) {
      Global.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có chắc chắn xóa ảnh này", 11);
    } else if (action.equals("Thêm ảnh")) {
      Category category = (Category) categories.elementAt(0);
      albumId = category.parent;
      
      Platform platform = Platform.getInstance();
      platform.addPictureImportEventHandler(this);
      platform.startPictureImport();
    } else if (action.equals("Tài khoản")) {
      if (type.equals("view_comment") || type.equals("view_comment_album")) {
        Comment comment = (Comment) comments.elementAt(commentIndex);
        _parameters.put("User", comment.userComment);
      } else if (type.equals("list_photo")) {
        Category category = (Category) categories.elementAt(0);
        _parameters.put("User", category.user);
      }
      FrmAccount.backForm = this;
      GameGlobal.nextState(FrmAccount.instance(), _parameters);
    } else if (action.equals("Bình luận")) {
      request(VIEW_COMMENT_REQUEST, new StringArray(new String[] { gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()), String.valueOf(commentStart), String.valueOf(commentEnd) },3));
      commentIndex = 0;
      if (comments != null) {
        comments.removeAllElements();
      }
      gridMenu.setVisible(false);
      // "Thích", "Xem album", "Kết bạn", "Menu MXH"
    } else if (action.equals("Thích") && type.equals("view_photo")) {
      request(LIKE_PHOTO_REQUEST, gridMenu.getTitleOfIndex(gridMenu.getCurrentSelectedIndex()));
    } else if (action.equals("Thích") && (type.equals("view_comment") || type.equals("view_comment_album"))) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      request(LIKE_COMMENT_REQUEST, new StringArray(new String[] { comment.id, type },2));
    } else if (action.equals("Xem album") && (type.equals("view_comment") || type.equals("view_comment_album"))) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      request(LIST_MY_ALBUM_REQUEST, new StringArray(new String[] { comment.userComment, String.valueOf(albumStart), String.valueOf(albumEnd) },3));
      clearCategory();
    } else if (action.equals("Xem tường") && (type.equals("view_comment") || type.equals("view_comment_album"))) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      _parameters.put("wallType", new Integer(1));
      _parameters.put("User", comment.userComment);
      FrmWall.backForm = backForm;
      Global.nextState(FrmWall.instance(), _parameters);
    } else if (action.equals("Kết bạn") && (type.equals("view_comment") || type.equals("view_comment_album"))) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      if (!comment.userComment.equals(Global.currentUser.getName())) {
        SocketClientUtil.addFriendRequest(comment.userComment);
      }
    } else if (action.equals("Xóa lời bình")) {
      Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Bạn có đồng ý xóa", "bình luận này?" ), 12);
    } else if (action.equals("Tìm kiếm")) {
      isSeachAlbum = true;
      txtInput.setVisible(true);
    }
    if (event.getSource() == gridMenu) {
      keyReleased(Key.FIRE);
      return;
    }
  }

  public void doTask() {
    Comment comment = (Comment) comments.elementAt(commentIndex);
    if (comment == null) {
      return;
    }
    int strWidth = text8.stringWidth(comment.comment);
    if (currentX + strWidth > 10) {
      currentX -= 2;
    } else {
      currentX = Global.getDefaultAvatar().getWidth() + 5;
    }
  }
}